package com.android.kmobi.locket.ui;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.kmobi.locket.R;
import com.android.kmobi.locket.mpcontrol.MpControl;
import com.android.publicModule.network.DownloadFile;
import com.android.publicModule.system.SystemInfo;
import com.android.publicModule.tools.Tools;

import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.webkit.JsPromptResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebStorage.QuotaUpdater;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

public class MainActivity extends Activity {

	private ProgressBar popProgressBar = null;
	private LinearLayout popWebViewLayout = null;
	private WebView view = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.e("muge","onCreate()");
		super.onCreate(savedInstanceState);
		
		//getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		
		final Window win = getWindow();
		  win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
		  | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
		  win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
		  | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
		
		  setContentView(R.layout.webview);	
		//getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);   //应用运行时，保持屏幕高亮，不锁屏
		Intent intent = this.getIntent();
		if(intent!=null)
		{
			Log.e("muge","MainActivity intent!=null");
			String action = intent.getAction();
			if(action!=null)
			{
				String from = intent.getStringExtra("from");
				if(action.equals(Intent.ACTION_SCREEN_ON))//屏亮
				{
					Log.e("muge","MainActivity 屏亮: ACTION_SCREEN_ON="+action+" from="+from);
				}
				else if(action.equals(Intent.ACTION_USER_PRESENT))//用户解锁
				{
					Log.e("muge","MainActivity 用户解锁:ACTION_USER_PRESENT="+action+" from="+from);
				}
				else if(action.equals(Intent.ACTION_SCREEN_OFF))//屏暗
				{
					Log.e("muge","MainActivity 屏暗:ACTION_SCREEN_OFF="+action+" from="+from);
				}
				else
				{
					Log.e("muge","MainActivity action="+action);
				}
			}
			else
			{
				Log.e("muge","MainActivity action=null");
			}
		}
		else
		{
			Log.e("muge","MainActivity intent=null");
		}
		MpControl.getInstance(this).init();
		
		
		//TODO 如下为webview相关代码
		popProgressBar = (ProgressBar)findViewById(R.id.popProgressBar);
		popWebViewLayout = (LinearLayout)findViewById(R.id.popWebViewLayout);
		
		view = new WebView(getApplicationContext());
		view.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		view.setSaveEnabled(false);
		popWebViewLayout.addView(view);
		
		//..WebSettings
		WebSettings mWebSettings = view.getSettings();  
		
		if (mWebSettings != null){	
			
			mWebSettings.setSavePassword(false);
			mWebSettings.setSaveFormData(false);   
			mWebSettings.setJavaScriptEnabled(true);  
			mWebSettings.setAllowFileAccess(true);
			mWebSettings.setPluginsEnabled(true);
			mWebSettings.setPluginState(PluginState.ON);
			mWebSettings.setAllowFileAccess(true);
			mWebSettings.setSupportZoom(false);
			if(SystemInfo.getAndroidSDKINT()>10)
			{
				mWebSettings.setDisplayZoomControls(false);
			}
		    
			//..cache优先
			mWebSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
			mWebSettings.setAppCacheEnabled(true);
			mWebSettings.setDatabaseEnabled(true); 			
			mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true); 

			/*
			if(new File(Tools.sdcardPath).exists())
			{
				mWebSettings.setAppCachePath(Tools.sdcardPath+"/lock/"); 
			}
			else
			{
				String dir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();   
				//设置应用缓存的路径   
				mWebSettings.setAppCachePath(dir); 
			}
			*/
			
			String dir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();   
			//设置应用缓存的路径   
			mWebSettings.setAppCachePath(dir); 
			
			//设置缓存的模式   
			//mWebSettings.setCacheMode(WebSettings.LOAD_DEFAULT);   
			//设置应用缓存的最大尺寸   
			mWebSettings.setAppCacheMaxSize(1024*1024*8);  	
		}
		
        //..
        //..JS脚本支持
		view.addJavascriptInterface(new JSActionInterface(), "webview");   
//        
        view.setWebViewClient(new JSWebViewClient());
        view.setWebChromeClient(new JSWebChromeClient()); 
		
        view.setBackgroundColor(0x00000000);
        
        String url = indexHtmlUrl;
        if(Tools.getPackageInfo(this, "com.adobe.flashplayer")==null)
        {
        	url = indexOnlyHtmlUrl;
        }
        //url = indexOnlyHtmlUrl;
        /*
        File f1 = new File(sdcardPath1);
        File f2 = new File(sdcardPath2);
        String url = indexHtmlUrl;
        if(f1.exists()&&f2.exists())
        {
        	//url = "file://"+sdcardPath1;
        }
        else
        {
        	//downloadThread();
        }
        */
        url="file:///sdcard/lock/lock.html";
		view.loadUrl(url);//http://fuzywujie.vicp.cc:9000/ps/admin/template/slide/slide.jsp?key=W_AD_bde9ae3b-b6e1-4589-b965-62be9d9077c1
		view.requestFocus();
	}
	
	private final static String domain = "http://ftp86627.host263.web522.com";//"http://ftp86627.host263.web522.com";//"http://192.168.1.22";
	private final static String indexOnlyHtml = "/lock/index-only.html";	
	private final static String indexHtml = "/lock/index.html";	
	private final static String indexSwf = "/lock/locket.swf";
	
	private final static String indexHtmlUrl = domain+indexHtml;
	
	private final static String indexSwfUrl = domain+indexSwf;
	
	private final static String indexOnlyHtmlUrl = domain+indexOnlyHtml;
	
	private final static String sdcardPath1 = Tools.sdcardPath+indexHtml;
	private final static String sdcardPath2 = Tools.sdcardPath+indexSwf;
	
	private Thread downloadThread;
	private void downloadThread() {
		if(downloadThread==null)
		{
			downloadThread = new Thread() {
				public void run() {
					DownloadFile mDownloadFile = new DownloadFile(MainActivity.this.getApplicationContext());
					
					mDownloadFile.downloadFile(indexHtmlUrl, sdcardPath1);
					
					mDownloadFile.downloadFile(indexSwfUrl, sdcardPath2);
					
					downloadThread = null;
				}
			};
			try {
				downloadThread.start();
			} catch(NullPointerException e) {
				
			} catch(IllegalThreadStateException e) {
				
			}
		}
	}

	public static void log(String msg){
		if (msg != null){
			Log.d("MainActivity", msg);
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem menu) {
		finish();
		return true;
	}
	
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        	finish();
        }
        return super.onKeyDown(keyCode, event);
    }
    
    @Override  
    protected void onStart() {
    	Log.e("muge","onStart()");
        super.onStart();
    }
    
    @Override
    protected void onRestart() {
    	Log.e("muge","onRestart()");
        super.onRestart();
    }

    private WakeLock mWakeLock;
    @Override  
    protected void onResume() {
    	Log.e("muge","onResume()");
        super.onResume();
        /*
        PowerManager pManager = ((PowerManager) getSystemService(POWER_SERVICE));  
        mWakeLock = pManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK  
                | PowerManager.ON_AFTER_RELEASE, "muge");  
        mWakeLock.acquire();  
        */
    }  
      
    @Override  
    protected void onPause() {
    	Log.e("muge","onPause()");
        super.onPause();  
        /*
        if(null != mWakeLock){  
            mWakeLock.release();  
        }
        */
    }
    
    @Override  
    protected void onStop() {
    	Log.e("muge","onStop()");
        super.onStop();
    }
    
    @Override  
    protected void onDestroy() {
    	Log.e("muge","onDestroy()");
        super.onDestroy();
    }

    private void jumpToPhone() {
    	Intent intent =new Intent();
    	intent.setAction(Intent.ACTION_CALL_BUTTON);//"android.intent.action.CALL_BUTTON"
    	startActivity(intent);
    }
    
    /**
     * 通过包名打开文件
     * @return
     */
    public boolean openApp(Context context, String packageName) {
        try {
            PackageManager packageManager = context.getPackageManager();
            Intent intent = packageManager.getLaunchIntentForPackage(packageName);
            if(intent!=null)
            {
	            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
	                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
	            if(context!=null)
	            {
	            	context.startActivity(intent);
	            	Tools.showLog("InstallAppHelper", "openApp() packageName="+packageName+" sucess");
	            	return true;
	            }
            }
        } catch (Exception e) {
        }
        Tools.showLog("InstallAppHelper", "openApp() packageName="+packageName+" fail");
        return false;
    }
    
    private void jumpToSms() {
    	Intent intent = new Intent(Intent.ACTION_VIEW);
    	intent.setType("vnd.android-dir/mms-sms");
    	List<ResolveInfo> list = Tools.queryIntentActivities(this, intent);
    	//intent.setData(Uri.parse("content://mms-sms/conversations/"));//此为号码 
    	String packageName = null;
    	if(list!=null&&list.size()>0)
    	{
    		ResolveInfo info = list.get(0);
    		if(info!=null)
    		{
    			ActivityInfo aInfo= info.activityInfo;
    			if(aInfo!=null)
    			{
    				packageName = aInfo.packageName;
    			}
    		}
    	}
    	if(packageName!=null&&packageName.length()>0)
    	{
    		openApp(this, packageName);
    	}
    	else
    	{
    		startActivity(intent);
    	}
    }
    
    private void jumpToCamera() {
    	Intent i = new Intent(Intent.ACTION_CAMERA_BUTTON, null);
    	this.sendBroadcast(i);
    }
    
    private void jumpToUrl(String url) {
    	if(url!=null&&url.length()>0)
    	{
    		if(!(url.startsWith("http://")||url.startsWith("https://")))
    		{
    			url = "http://"+url;
    		}
    		Tools.openURL(this, url);
    	}
    }

	/**
	 * @author jia.gui 
	 * @desc JavaScript Interface
	 */
	public class JSActionInterface {

		public boolean isPackageExist(final String packageName) {
			return Tools.getPackageInfo(MainActivity.this, packageName)!=null;
		}
		
		/**
		 * @author jia.gui
		 * @desc Web点击事件，用于JS中调用
		 */
		public void clickOnAndroid(final String json){
			
			log("clickOnAndroid json = " + json);
			
			if(json!=null&&json.length()>0)
			{
				try {
					JSONObject jsonObj = new JSONObject(json);
					if(jsonObj!=null)
					{
						String action = jsonObj.optString("action");
						String url = jsonObj.optString("url");
						int type = jsonObj.optInt("type");
						if(action.equals("lock"))
						{
							if(type==3)
							{
								MpControl.getInstance(MainActivity.this).playTone("lock.mp3");
							}
							else
							{
								finish();
							}
						}
						else if(action.equals("phone"))
						{
							if(type==3)
							{
								MpControl.getInstance(MainActivity.this).playTone("phone.mp3");
							}
							else
							{
								jumpToPhone();
								finish();
							}
						}
						else if(action.equals("sms"))
						{
							if(type==3)
							{
								MpControl.getInstance(MainActivity.this).playTone("sms.mp3");
							}
							else
							{
								jumpToSms();
								finish();
							}
						}
						else if(action.equals("camera"))
						{
							if(type==3)
							{
								MpControl.getInstance(MainActivity.this).playTone("camera.mp3");
							}
							else
							{
								jumpToCamera();
								finish();
							}
						}
						else if(action.equals("big"))
						{
							if(type==3)
							{
								
							}
							else
							{
								jumpToUrl(url);
								finish();
							}
						}
						else if(action.equals("web"))
						{
							if(type==3)
							{
								
							}
							else
							{
								jumpToUrl(url);
								finish();
							}
						}
						else if(action.equals("wap"))
						{
							if(type==3)
							{
								
							}
							else
							{
								jumpToUrl(url);
								finish();
							}
						}
						else
						{
							if(type==3)
							{
								
							}
							else
							{
								jumpToUrl(url);
								finish();
							}
						}
					}
				} catch (JSONException e) {
				}
			}
			
			//finish();
		}		
	}
	
	/**    
     * @author jia.gui
     * @desc 普通url链接load数据
     */ 
	class JSWebViewClient extends WebViewClient { 

		@Override
		public void onFormResubmission(WebView view, Message dontResend,
				Message resend) {
			log("onFormResubmission");
			resend.sendToTarget();
			// TODO Auto-generated method stub
			//super.onFormResubmission(view, dontResend, resend);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
    		
			log("onPageFinished");
			
    		//WebADUtils.log("onPageFinished");
			if (popProgressBar != null){
				popProgressBar.setVisibility(View.GONE);	
			}
			
			// TODO Auto-generated method stub
			super.onPageFinished(view, url);
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			
			log("onPageStarted");
			
			//WebADUtils.log("onPageStarted");
			if (popProgressBar != null){
				popProgressBar.setVisibility(View.VISIBLE);	
			}
			// TODO Auto-generated method stub
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
		
			// TODO Auto-generated method stub
			super.onReceivedError(view, errorCode, description, failingUrl);
		}

		@Override
		public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
			
			log("shouldOverrideKeyEvent KeyCode = " + event.getKeyCode() + ", Action = " + event.getAction());
			
			// TODO Auto-generated method stub
			//return super.shouldOverrideKeyEvent(view, event);
			return true;
		}

		@Override 
    	public boolean shouldOverrideUrlLoading(WebView view, String url) { 
	    	//view.loadUrl(url); 
	    	return false; 
    	} 
    }
	
	/**    
     * @author jia.gui
     * @desc 重载
     */ 
    final class JSWebChromeClient extends WebChromeClient {   
    	
        @Override
		public void onProgressChanged(WebView view, int newProgress) {
        	
			if (popProgressBar != null
					&& popProgressBar.getVisibility() == View.VISIBLE
					&& newProgress > 0 && newProgress % 3 == 0){
				popProgressBar.setProgress(newProgress);
			}
			
			// TODO Auto-generated method stub
			super.onProgressChanged(view, newProgress);
		}
        
        /**    
         * 处理prompt弹出框    
         */     
        @Override     
        public boolean onJsPrompt(WebView view, String url, String message,      
                String defaultValue, JsPromptResult result) { 
        	
        	log("onJsPrompt message = " + message);
            result.confirm();      
            return super.onJsPrompt(view, url, message, message, result);      
        }

		@Override
		public void onExceededDatabaseQuota(String url,
				String databaseIdentifier, long quota,
				long estimatedDatabaseSize, long totalQuota,
				QuotaUpdater quotaUpdater) {
			quotaUpdater.updateQuota(20480l);		
		}    
        
    }
    
}
